package com.ljyanimo.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljyanimo.entity.SysUser;
import com.ljyanimo.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Shiro Realm
 * @author Animo
 * @Date 2020/9/29
 * @Blog http://www.ljyanimo.com
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 获取登录用户名
        String principal = authenticationToken.getPrincipal().toString();

        SysUser sysUser = iSysUserService.getOne(new QueryWrapper<SysUser>().eq("account", principal));
        if(sysUser == null){
            throw new UnknownAccountException("未知账号");
        }
        if(sysUser.getActive() == 1){
            throw new DisabledAccountException("账号已被禁用");
        }
        // 这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                sysUser,
                sysUser.getPassword(),
                ByteSource.Util.bytes(sysUser.getSalt()),
                getName());
        return simpleAuthenticationInfo;

    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser = (SysUser)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermission("sys:test");
        return authorizationInfo;
    }

}
